import React, { useState } from 'react';
import { IonCard, IonCardHeader, IonCardTitle, IonCardContent, IonItem, IonLabel, IonSelect, IonSelectOption, IonButton, IonTextarea, IonToggle, IonNote } from '@ionic/react';
import { useOllama } from '../../hooks/useOllama';
import { useTranslation } from 'react-i18next';

interface ModelRunConfig {
  model: string;
  prompt: string;
  format: 'json' | 'text';
  keepAlive: string;
  insecure: boolean;
  wordWrap: boolean;
}

const ModelManagement: React.FC = () => {
  const { models, runModel, isLoading, error } = useOllama();
  const { t } = useTranslation();
  const [config, setConfig] = useState<ModelRunConfig>({
    model: '',
    prompt: '',
    format: 'text',
    keepAlive: '5m',
    insecure: false,
    wordWrap: true
  });
  const [output, setOutput] = useState<string>('');

  const handleConfigChange = (key: keyof ModelRunConfig, value: any) => {
    setConfig(prev => ({ ...prev, [key]: value }));
  };

  const handleRunModel = async () => {
    try {
      const result = await runModel(config.model, config.prompt);
      setOutput(result.output);
    } catch (error) {
      console.error('Failed to run model:', error);
    }
  };

  return (
    <IonCard>
      <IonCardHeader>
        <IonCardTitle>{t('models.manage.title')}</IonCardTitle>
      </IonCardHeader>
      <IonCardContent>
        <div className="space-y-4">
          {/* Model Selection and Configuration */}
          <div className="space-y-2">
            <IonItem>
              <IonLabel position="stacked">{t('models.fields.name')}</IonLabel>
              <IonSelect
                value={config.model}
                onIonChange={e => handleConfigChange('model', e.detail.value)}
              >
                {models.map(model => (
                  <IonSelectOption key={model.name} value={model.name}>
                    {model.name}
                  </IonSelectOption>
                ))}
              </IonSelect>
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('models.manage.prompt')}</IonLabel>
              <IonTextarea
                value={config.prompt}
                onIonChange={e => handleConfigChange('prompt', e.detail.value!)}
                placeholder={t('models.manage.promptPlaceholder')}
                rows={4}
              />
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('models.manage.format')}</IonLabel>
              <IonSelect
                value={config.format}
                onIonChange={e => handleConfigChange('format', e.detail.value)}
              >
                <IonSelectOption value="text">{t('models.manage.formatOptions.text')}</IonSelectOption>
                <IonSelectOption value="json">{t('models.manage.formatOptions.json')}</IonSelectOption>
              </IonSelect>
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('models.manage.keepAlive')}</IonLabel>
              <IonSelect
                value={config.keepAlive}
                onIonChange={e => handleConfigChange('keepAlive', e.detail.value)}
              >
                <IonSelectOption value="5m">5 minutes</IonSelectOption>
                <IonSelectOption value="10m">10 minutes</IonSelectOption>
                <IonSelectOption value="30m">30 minutes</IonSelectOption>
                <IonSelectOption value="custom">Custom</IonSelectOption>
              </IonSelect>
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('models.manage.insecure')}</IonLabel>
              <IonToggle
                checked={config.insecure}
                onIonChange={e => handleConfigChange('insecure', e.detail.checked)}
              />
              <IonNote>{t('common.enabled')}</IonNote>
            </IonItem>

            <IonItem>
              <IonLabel position="stacked">{t('models.manage.wordWrap')}</IonLabel>
              <IonToggle
                checked={config.wordWrap}
                onIonChange={e => handleConfigChange('wordWrap', e.detail.checked)}
              />
              <IonNote>{t('common.enabled')}</IonNote>
            </IonItem>
          </div>

          {/* Error Display */}
          {error && (
            <div className="alert alert-error">
              <span>{error}</span>
            </div>
          )}

          {/* Run Button */}
          <div className="flex justify-end">
            <IonButton
              onClick={handleRunModel}
              disabled={isLoading || !config.model || !config.prompt}
            >
              {isLoading ? t('models.manage.running') : t('models.manage.run')}
            </IonButton>
          </div>

          {/* Output Display */}
          {output && (
            <div className="mt-4">
              <h3 className="text-lg font-semibold mb-2">{t('models.manage.output')}</h3>
              <div className={`p-4 bg-base-200 rounded-lg font-mono whitespace-pre-wrap ${config.wordWrap ? 'break-words' : 'overflow-x-auto'}`}>
                {output}
              </div>
            </div>
          )}

          {/* Help/Info Section */}
          <div className="mt-4 p-4 bg-base-200 rounded-lg">
            <h3 className="text-lg font-semibold mb-2">{t('models.manage.help.title')}</h3>
            <p className="text-sm">
              {t('models.manage.help.description')}
            </p>
          </div>
        </div>
      </IonCardContent>
    </IonCard>
  );
};

export default ModelManagement; 